Mongoose Schema

We have connected our application to our MongoDB cluster in the cloud. Next, let's store some data! Before doing so, we need to understand how MongoDB organizes data.

A Mongo Database is made up of collections and documents.

A collection represents a single entity in your app. For example, in a note taking app, you would have entities like "notes" and "users". Each of such entities will be a single collection in our database.

A collection contains documents. A document is an instance of the entity represented by the collection. For example, a collection called notes will have documents, each representing a "note." Each "note" document would contain the attributes that make up a note (such as "title," "text," etc.).

A document in MongoDB looks a lot like a JSON object.

Suppose you have never worked with a database. In that case, it may be helpful to think about collections as folders and documents as files organized inside the folders.

If you have experience working with databases, it most likely has been with a Relational database. (For those who never heard of it, you can think of relational databases like spreadsheets where data is structured in tables and each entry is a row in a table.) MongoDB is not a relational database, although you can think of collections as tables and documents as the rows (records) in a table.

Schema

According to MongoDB documentation:

A document schema is a JSON object that allows you to define the shape and content of documents embedded in a collection.

For example, you can use a schema to require a specific set of fields, configure a field's content, or validate changes to a document based on its beginning and end states.

As an example, we will define a schema for "note" documents.

import mongoose from "mongoose";

const NoteSchema = new mongoose.Schema({
  title: { type: String },
  text: { type: String },
});

export default NoteSchema

We are using the Schema class from Mongoose to create a document schema for notes. The code snippet above essentially establishes that a note will have a title and a text, and both of these attributes are of type String.